package com.mitac.mcd.cs.mobiletracking.socketserver;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.mitac.mcd.cs.mobiletracking.socketserver.util.BusinessUtil;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.DBConnection;

public class CheckOnlineClient extends Thread {

	MobileServer obj = null;
	private boolean _run = true;
	private List<String> realOnlineClient = null;
	
	public CheckOnlineClient(MobileServer mobileServerObj){
		this.obj = mobileServerObj;
		this.start();
	}
	
	public void run() {
		BusinessUtil.aLogger.info("新开CheckOnlineClient线程...");
		while(_run){
			try {
				Thread.sleep(5*60*1000);//5 min
			} catch (InterruptedException e) {
				BusinessUtil.aLogger.info("SERVER_ID:"+obj.SERVER_ID+" 对应的MobileServer线程sleep异常:"+e);
			}
			realOnlineClient = new ArrayList<String>();
			
			for(Iterator<String> it = obj.outputStreams.keySet().iterator(); it.hasNext();){
                String uuid = (String)it.next();
                realOnlineClient.add(uuid);
            }
			List<String> dbOnlinelist = getOnlineClientFromDB();
			//begin check
			List<String> non_inserted_uuid = new ArrayList<String>();
			List<String> non_exist_uuid = new ArrayList<String>();
			//发现实际在线，而未写入db的client
			for(String uuid:realOnlineClient){
				boolean flag = true;
				for(String dbuuid:dbOnlinelist){
					if (uuid.equals(dbuuid)){
						flag = false;
					}
				}
				if (flag){//有在线的client而并未存入DB
					BusinessUtil.aLogger.info(uuid+"对应的client未存入db中online client...");
					non_inserted_uuid.add(uuid);
				}
			}
			//发现db中存在，而实际并不在线的client
			for (String dbuuid:dbOnlinelist){
				boolean flag = true;
				for(String uuid:realOnlineClient){
					if (uuid.equals(dbuuid)){
						flag = false;
					}
				}
				if (flag){//db中存在而实际并不在线的client
					BusinessUtil.aLogger.info(dbuuid+"对应的client在db中存在而实际并不在线...");
					non_exist_uuid.add(dbuuid);
				}
			}
			//insert
			setOnlineClient(non_inserted_uuid);
			//delete
			removeClientFromDB(non_exist_uuid);
		}
	}
	
	private List<String> getOnlineClientFromDB(){
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	ResultSet rs = null;
    	List<String> list = new ArrayList<String>();
        String sqlA = " select uuid from ONLINE_CLIENT where SERVER_ID = ? " ;
        try {
            dbc = DBConnection.getConnection("gpsdata");
			pst = dbc.prepareStatement(sqlA);
			pst.setInt(1, obj.SERVER_ID);
			rs = pst.executeQuery();
			while(rs.next()){
				list.add(rs.getString("uuid"));
			}

			if(null!=rs) rs.close();
            dbc.close();
            pst.close();
		} catch (Exception e) {
			BusinessUtil.aLogger.info("getOnlineClientFromDB:"+e);
		}
		return list;
	}
	
	private void setOnlineClient(List<String> uuidArray){
		if (uuidArray==null||uuidArray.size()==0){
			return;
		}
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
		String sqlA = " insert into ONLINE_CLIENT " +
		"(UUID,USER_ID,LOGIN_TIME,SERVER_ID,NOTE) values " +
		"(?,?,?,?,?) ";
		try {
            dbc = DBConnection.getConnection("gpsdata");
			pst = dbc.prepareStatement(sqlA);
			for(String uuid:uuidArray){
				Date date = new Date();
				pst.setString(1, uuid);
				pst.setInt(2, Integer.parseInt(MobileServer.uuidUseridList.get(uuid)));
				pst.setTimestamp(3, new java.sql.Timestamp(date.getTime()));
				pst.setInt(4,obj.SERVER_ID);
				pst.setString(5, null);
				pst.addBatch();
			}
			pst.executeBatch();
			
			dbc.close();
            pst.close();
		} catch (Exception e) {
			BusinessUtil.aLogger.info("setOnlineClient:"+e);
		}
	}
	
	private void removeClientFromDB(List<String> uuidArray){
		if (uuidArray==null||uuidArray.size()==0){
			return;
		}
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
		String sqlA = " delete from ONLINE_CLIENT where UUID = ? and SERVER_ID = ? " ;
		try {
            dbc = DBConnection.getConnection("gpsdata");
			pst = dbc.prepareStatement(sqlA);
			for(String uuid:uuidArray){
				pst.setString(1, uuid);
				pst.setInt(2, obj.SERVER_ID);
				pst.addBatch();
			}
			pst.executeBatch();
			
            dbc.close();
            pst.close();
		} catch (Exception e) {
			BusinessUtil.aLogger.info("removeClientFromDB:"+e);
		}
	}
	
	public void stopThread() {
        this._run = false;
    }
	
}
